<template>
    <div class="product-purchase">
      <h2>商品购买</h2>
      <el-row :gutter="20">
        <el-col :span="8" v-for="product in products" :key="product.id">
          <el-card class="product-card">
            <div slot="header" class="clearfix">
              <span>{{ product.name }}</span>
              <span class="price">{{ '¥' + product.price }}</span>
            </div>
            <div class="product-content">
              <el-image :src="product.imageUrl" fit="cover"></el-image>
              <el-button type="primary" @click="addToCart(product)">加入购物车</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  import { ElRow, ElCol, ElCard, ElImage, ElButton } from 'element-plus';
  
  const products = ref([
    { id: 1, name: '手机', price: 1999, imageUrl: 'https://gw.alicdn.com/imgextra/i4/838801383/O1CN015LFsKq1M5SdR068rQ_!!838801383.jpg_Q75.jpg_.webp' },
    { id: 2, name: '电视', price: 3999, imageUrl: 'https://gw.alicdn.com/imgextra/i1/3378707715/O1CN01k4agFV26rW9x98sg6_!!3378707715.jpg_Q75.jpg_.webp' },
    { id: 3, name: '笔记本电脑', price: 5999, imageUrl: 'https://gw.alicdn.com/imgextra/i3/2217253746347/O1CN01ArfLLU1wkympkEz4z_!!2217253746347.jpg_Q75.jpg_.webp'},
    { id: 4, name: '空调', price: 1999, imageUrl: 'https://gw.alicdn.com/imgextra/i1/2217210414452/O1CN01CirYkR1il4FPEKzSn_!!2217210414452.jpg_Q75.jpg_.webp' },
    { id: 5, name: '洗衣机', price: 3999, imageUrl: 'https://gw.alicdn.com/imgextra/i2/2216491575256/O1CN0133cRgB1ohIgDB8l6Z_!!2216491575256.jpg_Q75.jpg_.webp' },
    { id: 6, name: '冰箱', price: 5999, imageUrl: 'https://gw.alicdn.com/imgextra/i4/2215561855927/O1CN01lSPFla1tecRajntRG_!!2215561855927.jpg_Q75.jpg_.webp'}
  ]);
  
  const cart = ref([]);
  
  const addToCart = (productToAdd) => {
    const existingProduct = cart.value.find(product => product.id === productToAdd.id);
    if (existingProduct) {
      existingProduct.quantity++;
    } else {
      cart.value.push({ ...productToAdd, quantity: 1 });
    }
    localStorage.setItem('cart', JSON.stringify(cart.value));
    ElMessage({
      message: '商品已加入购物车',
      type: 'success'
    });
  };
  </script>
  
  <style scoped>
  .product-purchase {
    padding: 20px;
  }
  .product-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 10px;
  }
  .price {
    float: right;
    font-weight: bold;
    color: #f56c6c;
  }
  .product-content {
    padding: 20px;
    text-align: center;
  }
  </style>
  